package com.earthea.datasource.lock;

import cn.hutool.core.date.DatePattern;
import com.earthea.common.util.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author zhysunny
 * @date 2020/12/15 23:11
 */
@Slf4j
@Repository
@EnableTransactionManagement
public class LockRepository {

    @Autowired
    private LockMapper lockMapper;

    public boolean tryLock(String lockId, long timeout) {
        LockEntity lockEntity = lockMapper.getLock(lockId);
        if (lockEntity == null) {
            lockEntity = new LockEntity(lockId, timeout);
            lockMapper.add(lockEntity);
        }
        if (lockEntity.getStatus() != 1) {
            log.debug("get lock version is {}", lockEntity.getVersion());
            lockEntity.setStatus(1);
            lockEntity.setClientIp(IpUtils.getLocalIp());
            return lockMapper.tryLock(lockEntity) > 0;
        }
        return false;
    }

    public void unLock(String lockId) {
        lockMapper.unLock(lockId);
    }

    public boolean isTimeout(String lockId) {
        LockEntity lockEntity = lockMapper.getLock(lockId);
        if (lockEntity == null) {
            return false;
        } else {
            long timeout = lockEntity.getTimeout();
            String time = LocalDateTime.now().minusSeconds(timeout).format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN));
            return time.compareTo(lockEntity.getUpdateTime()) > 0;
        }
    }

    public void create() {
        lockMapper.create();
    }

}
